import { useState, useEffect } from 'react';
import * as Storage from './src/utils/Storage';
import { changeKM, changeNAME, changeHEAD } from './src/store/device/actions';

export const useInitLocale = store => {
  const { dispatch } = store;
  const [isAppReady, setIsAppReady] = useState(false);

  useEffect(() => {
    async function initLocale() {
      const defKM = await Storage.get(Storage.SET_KM);
      if (defKM) {
        await dispatch(changeKM(defKM));
      }

      const defNAME = await Storage.get(Storage.NICKNAME);
      if (defKM) {
        await dispatch(changeNAME(defNAME));
      } else {
        var code = '' + (parseInt(Math.random() * 1000000) + 1000000);
        code = code.substring(1, 7);
        await dispatch(changeNAME('Rawrr_' + code));
        await Storage.save(Storage.NICKNAME, 'Rawrr_' + code);
      }

      const defHead = await Storage.get(Storage.HEAD);
      if (defHead) {
        await dispatch(changeHEAD(defHead));
      }

      setIsAppReady(true);
    }

    initLocale();
  }, [dispatch]);

  return { isAppReady, setIsAppReady };
};
